package cn.iocoder.yudao.module.wine.service.commissionrate;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.module.wine.controller.admin.commissionrate.vo.*;
import cn.iocoder.yudao.module.wine.dal.dataobject.commissionrate.CommissionRateDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.wine.dal.mysql.commissionrate.CommissionRateMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wine.enums.ErrorCodeConstants.*;

/**
 * 佣金比例配置 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class CommissionRateServiceImpl implements CommissionRateService {

    @Resource
    private CommissionRateMapper commissionRateMapper;

    @Override
    public Long createCommissionRate(CommissionRateSaveReqVO createReqVO) {
        // 插入
        CommissionRateDO commissionRate = BeanUtils.toBean(createReqVO, CommissionRateDO.class);
        commissionRateMapper.insert(commissionRate);
        // 返回
        return commissionRate.getId();
    }

    @Override
    public void updateCommissionRate(CommissionRateSaveReqVO updateReqVO) {
        // 校验存在
        validateCommissionRateExists(updateReqVO.getId());
        if (updateReqVO.getRatio()> 100 || updateReqVO.getRatio() < 0){
            throw exception(ILLEGAL_VALUE);
        }
        // 更新
        CommissionRateDO updateObj = BeanUtils.toBean(updateReqVO, CommissionRateDO.class);
        commissionRateMapper.updateById(updateObj);
    }

    @Override
    public void deleteCommissionRate(Long id) {
        // 校验存在
        validateCommissionRateExists(id);
        // 删除
        commissionRateMapper.deleteById(id);
    }

    private void validateCommissionRateExists(Long id) {
        if (commissionRateMapper.selectById(id) == null) {
            throw exception(INFO_NOT_EXISTS);
        }
    }

    @Override
    public CommissionRateDO getCommissionRate(Long id) {
        return commissionRateMapper.selectById(id);
    }

    @Override
    public PageResult<CommissionRateDO> getCommissionRatePage(CommissionRatePageReqVO pageReqVO) {
        return commissionRateMapper.selectPage(pageReqVO);
    }

    @Override
    public CommissionRateDO getCommissionRateInfo() {

        return commissionRateMapper.selectOne(new QueryWrapper<>());
    }

}
